package com.ruoyi.web.controller.campus;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.campus.domain.Area;
import com.ruoyi.campus.service.IAreaService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 区域信息Controller
 * 
 * @author ruoyi
 * @date 2025-06-29
 */
@Api(tags = "区域信息管理")
@RestController
@RequestMapping("/campus/area")
public class AreaController extends BaseController
{

    @Autowired
    private IAreaService areaService;

    /**
     * 查询区域信息列表
     */
    @ApiOperation("查询区域信息列表")
    @RequiresPermissions("campus:area:list")
    @GetMapping("/list")
    public TableDataInfo list(Area area)
    {
        startPage();
        List<Area> list = areaService.selectAreaList(area);
        return getDataTable(list);
    }

    /**
     * 查询区域树形结构列表
     */
    @ApiOperation("查询区域树形结构列表")
    @RequiresPermissions("campus:area:list")
    @GetMapping("/tree")
    public AjaxResult tree(Area area)
    {
        try
        {
            // 参数校验和默认值设置
            if (area == null)
            {
                area = new Area();
            }
            
            // 查询区域列表
            List<Area> areas = areaService.selectAreaTreeList(area);
            
            // 如果没有数据，直接返回空列表
            if (areas == null || areas.isEmpty())
            {
                return AjaxResult.success(new ArrayList<>());
            }
            
            // 构建树形结构
            List<Area> treeData = areaService.buildAreaTree(areas);
            
            return AjaxResult.success(treeData);
        }
        catch (Exception e)
        {
            logger.error("查询区域树形结构失败", e);
            return AjaxResult.error("查询区域树形结构失败：" + e.getMessage());
        }
    }

    /**
     * 获取区域下拉树列表
     */
    @ApiOperation("获取区域下拉树列表")
    @GetMapping("/treeselect")
    public AjaxResult treeselect(Area area)
    {
        List<Area> areas = areaService.selectAreaTreeList(area);
        return AjaxResult.success(areaService.buildAreaTreeSelect(areas));
    }

    /**
     * 根据父区域ID查询子区域列表
     */
    @ApiOperation("根据父区域ID查询子区域列表")
    @RequiresPermissions("campus:area:list")
    @GetMapping("/children/{parentId}")
    public AjaxResult getChildren(@PathVariable Long parentId)
    {
        Area area = new Area();
        area.setParentId(parentId);
        List<Area> list = areaService.selectAreaList(area);
        return AjaxResult.success(list);
    }

    /**
     * 导出区域信息列表
     */
    @ApiOperation("导出区域信息列表")
    @RequiresPermissions("campus:area:export")
    @Log(title = "区域信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(Area area)
    {
        List<Area> list = areaService.selectAreaList(area);
        ExcelUtil<Area> util = new ExcelUtil<Area>(Area.class);
        return util.exportExcel(list, "区域信息数据");
    }



    /**
     * 新增保存区域信息
     */
    @ApiOperation("新增保存区域信息")
    @RequiresPermissions("campus:area:add")
    @Log(title = "区域信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult addSave(@RequestBody Area area)
    {
        if (!areaService.checkAreaNameUnique(area).equals("0"))
        {
            return AjaxResult.error("新增区域'" + area.getAreaName() + "'失败，区域名称已存在");
        }
        area.setCreateBy(getLoginName());
        return toAjax(areaService.insertArea(area));
    }

    /**
     * 修改区域信息
     */
    @ApiOperation("查询区域信息")
    @RequiresPermissions("campus:area:get")
    @GetMapping("/{areaId}")
    public AjaxResult getById(@PathVariable("areaId") Long areaId)
    {
        return AjaxResult.success(areaService.selectAreaByAreaId(areaId));
    }

    /**
     * 修改保存区域信息
     */
    @ApiOperation("修改保存区域信息")
    @RequiresPermissions("campus:area:edit")
    @Log(title = "区域信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult editSave(@RequestBody Area area)
    {
        if (!areaService.checkAreaNameUnique(area).equals("0"))
        {
            return AjaxResult.error("修改区域'" + area.getAreaName() + "'失败，区域名称已存在");
        }
        else if (area.getParentId() != null && area.getParentId().equals(area.getAreaId()))
        {
            return AjaxResult.error("修改区域'" + area.getAreaName() + "'失败，上级区域不能是自己");
        }
        // 验证父区域是否存在（允许parentId为null或0，表示根节点）
        else if (area.getParentId() != null && !area.getParentId().equals(0L))
        {
            Area parentArea = areaService.selectAreaByAreaId(area.getParentId());
            if (parentArea == null)
            {
                return AjaxResult.error("修改区域'" + area.getAreaName() + "'失败，上级区域不存在");
            }
        }
        area.setUpdateBy(getLoginName());
        return toAjax(areaService.updateArea(area));
    }

    /**
     * 删除区域信息
     */
    @ApiOperation("删除区域信息")
    @RequiresPermissions("campus:area:remove")
    @Log(title = "区域信息", businessType = BusinessType.DELETE)
    @DeleteMapping( "/{ids}")
    public AjaxResult remove(@PathVariable String ids)
    {
        return toAjax(areaService.deleteAreaByAreaIds(ids));
    }

    /**
     * 校验区域名称
     */
    @ApiOperation("校验区域名称")
    @PostMapping("/checkAreaNameUnique")
    public String checkAreaNameUnique(@RequestBody Area area)
    {
        return areaService.checkAreaNameUnique(area);
    }
}
